package com.bee.web.security;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author liuzy
 * @since 2015年5月22日
 */
public class Util {

    /**
     * 保存密钥到文件
     *
     * @param keyBytes
     * @param filePath
     */
    public static void outKeyFile(byte[] keyBytes, String filePath) {
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(keyBytes);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取密钥文件
     *
     * @param filePath
     * @return
     */
    public static byte[] readeKeyFile(String filePath) {
        byte[] keyBytes = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);
            keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return keyBytes;
    }

    public static String bytesToHexStr(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            String hv = Integer.toHexString(bytes[i] & 0xFF);
            if (hv.length() == 1) {
                sb.append(0);
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    public static byte[] hexStrToBytes(String hexString) {
        String hex = "0123456789ABCDEF";
        if (hexString == null || "".equals(hexString)) {
            return null;
        }
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toUpperCase().toCharArray();
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            bytes[i] = (byte) (hex.indexOf(hexChars[pos]) << 4 | hex.indexOf(hexChars[pos + 1]));

        }
        return bytes;
    }

}
